<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Loader;
use think\Request;

class FbaccountController extends AdminBaseController
{
	public function index()
	{
		$content = hook_one('admin_fbaccount_index_view');
		if (!empty($content)) {
			return $content;
		}

		$where = ['id' => ['neq', 0]];
		/**搜索条件**/
		$search_word = $this->request->param('search_word');
		if ($search_word) {
			$where['fbaccount_num|fbaccount_name|fbaccount_nick'] = ['like', "%$search_word%"];

		}


		$fbaccountList = Db::name('fbaccount')
			->where($where)
			->order("id DESC")
			->paginate(50);

		$fbaccountList->appends(['fbaccount_num|fbaccount_name|fbaccount_nick' => $search_word]);
		// 获取分页显示
		$page = $fbaccountList->render();

		$this->assign("page", $page);
		$this->assign("fbaccountList", $fbaccountList);
		return $this->fetch();
	}

	public function add()
	{
		return $this->fetch();
	}

	public function addPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['fbaccount_num'])) {
				$listArr = $this->checkexists();
				$_POST["create_time"] = date("Y-m-d H:i:s");

				$_POST["fbaccount_agent"] 	= trim($_POST["fbaccount_agent"]);
				$_POST["fbaccount_num"] 	= trim($_POST["fbaccount_num"]);
				$_POST["fbaccount_name"] 	= trim($_POST["fbaccount_name"]);
				$_POST["fbaccount_nick"] = md5($_POST["fbaccount_name"]);
				$_POST["opreate_id"] = session('ADMIN_ID');

				if(in_array($_POST["fbaccount_nick"], $listArr)){
					$fbaccount_name = $_POST['fbaccount_name'];
					echo 'test';
					exit;
					// $this->error("账户名称 $fbaccount_name 已存在~");
				}
				$result	= DB::name('fbaccount')->insertGetId($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("fbaccount/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("fb账户编号能为空！");
			}
		}
	}

	public function edit()
	{
		$content = hook_one('admin_fbaccount_edit_view');

		if (!empty($content)) {
			return $content;
		}

		$id      = $this->request->param('id', 0, 'intval');
		$fbaccount = DB::name('fbaccount')->where(["id" => $id])->find();
		$this->assign($fbaccount);
		return $this->fetch();
	}

	public function editPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['id'])) {
				$_POST["create_time"] = date("Y-m-d H:i:s");
				$_POST["fbaccount_agent"] 	= trim($_POST["fbaccount_agent"]);
				$_POST["fbaccount_num"] 	= trim($_POST["fbaccount_num"]);
				// $_POST["opreate_id"] = session('ADMIN_ID');
				$result = DB::name('fbaccount')->update($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("fbaccount/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("ID不能为空！");
			}
		}
	}

	public function delete()
	{
		$id = $this->request->param('id', 0, 'intval');

		if (Db::name('fbaccount')->delete($id) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	public function checkexists(){
		$fbaccountLists = array();
		$fbaccountList = Db::name('fbaccount') ->field('fbaccount_nick')->select()->toArray();
		foreach ($fbaccountList as $k => $v) {
			$fbaccountLists[] = $v['fbaccount_nick'];
		}
		return $fbaccountLists;
	}


	public function fileupload(){
		if ($this->request->isPost()) {
			if (!empty($_POST['upload_filename'])) {
				if($_POST['upload_filename'] && $_POST['upload_filename_url1']){
					$_POST['upload_filename'] = 'upload/'.$_POST['upload_filename_url1'];
				}
				$file_path = $_POST['upload_filename'];
				$this->dataexport($file_path);
			} else {
				$this->error("没有文件");
			}
		}
	}


	public function dataexport($filePath){
		Loader::import("PHPExcel.PHPExcel");
        Loader::import("PHPExcel.PHPExcel.Writer.Excel5");
        Loader::import("PHPExcel.PHPExcel.Writer.Excel2007");
        Loader::import("PHPExcel.PHPExcel.IOFactory");

       // $filePath = '/var/www/url.thinkcmf.com/test.xls';
       $objPHPExcel    = new \PHPExcel();
       /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/ 
	   $PHPReader = new \PHPExcel_Reader_Excel2007(); 
	    if(!$PHPReader->canRead($filePath)){ 
	       $PHPReader = new \PHPExcel_Reader_Excel5(); 
	       if(!$PHPReader->canRead($filePath)){ 
		         echo 'NO FILE'; 
		         return; 
	       } 
	     }

	    $PHPExcel = $PHPReader->load($filePath); 
		$currentSheet = $PHPExcel->getSheet(0);  //读取excel文件中的第一个工作表
		$allColumn = $currentSheet->getHighestColumn(); //取得最大的列号
		$allRow = $currentSheet->getHighestRow(); //取得一共有多少行

		// $erp_orders_id = array();  //声明数组
		for($currentRow = 2; $currentRow <= $allRow; $currentRow++){ 
			for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){ 
				$address = $currentColumn . $currentRow; 
				$data[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
			}
		}

		foreach ($data as $k => $v) {
			$urlName = trim($v['A']);
			$fileArr['fbaccount_agent'] = trim($v['A']); 
			$fileArr['fbaccount_num'] = trim($v['B']); 
			$fileArr['fbaccount_name'] = trim($v['C']); 

			$fileArr['fbaccount_nick'] = md5($fileArr['fbaccount_name']);
			$fileArr["opreate_id"] = session('ADMIN_ID');
			$fileArr['create_time'] = date('Y-m-d H:i:s'); 
			DB::name('fbaccount')->insertGetId($fileArr);
			// if(in_array($urlName, $urlmangerListArr)){
			// 	$fileArr['id'] = $urlmangerListIdArr[$urlName];
			// 	DB::name('urlmanger')->update($fileArr);
			// }else{
			// 	DB::name('urlmanger')->insertGetId($fileArr);
			// }
		}
		$this->success("添加成功！", url("fbaccount/index"));
	}

	#数据导出
	public function currdatexport() {

        Loader::import("PHPExcel.PHPExcel");
        Loader::import("PHPExcel.PHPExcel.Writer.Excel5");
        Loader::import("PHPExcel.PHPExcel.Writer.Excel2007");
        Loader::import("PHPExcel.PHPExcel.IOFactory");

        $objPHPExcel    = new \PHPExcel();
        $objWriter      = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter      = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        //查询时间段
        // $date_stop_s = $this->request->param('date_stop_s');
        // $date_stop_e = $this->request->param('date_stop_e');
        // $where['date_stop'] = ['between', "$date_stop_s,$date_stop_e"];
        $where['id'] = ['neq', "0"];

        // $currentDay = date("Y-m-d", strtotime("-2 days"));
        // $where['date_stop'] = ['like', "$currentDay"];
        // $where['date_stop'] = ['like', "2019-07-06"];
        $fbaccountList = Db::name('fbaccount')->where($where)->order('id DESC')->select()->toArray();


        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '序号')
        ->setCellValue('B1', '账户代理')
        ->setCellValue('C1', '账户编号')
        ->setCellValue('D1', '账户名称')
        ->setCellValue('E1', '账户编码');

        #用户
		foreach($fbaccountList as $k => $v){
			$objPHPExcel->getActiveSheet()->setCellValue('A' . ($k+2), ($k+1));
            $objPHPExcel->getActiveSheet()->setCellValue('B' . ($k+2), $v['fbaccount_agent']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . ($k+2), $v['fbaccount_num']);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . ($k+2), $v['fbaccount_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . ($k+2), $v['fbaccount_nick']);
		}

        $objPHPExcel->getActiveSheet()->settitle(date("Y-m-d")); //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0); //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="各家代理账户.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
        exit;
	}
}